#!/usr/bin/env bash

##
#  Docker-machine 搭建 etcd 集群
#  
##
set -e

AllNode=(manager1 worker1 worker2)

#  创建机器
create_cluster_mathine(){
    echo Creating cluster mathine
    for node in ${AllNode[@]};do
        docker-machine create -d virtualbox \
            --engine-registry-mirror https://dh7glme6.mirror.aliyuncs.com $node
    done
}

# 获取机器对应的ip 集合
declare -A  AllNodeDict
createDictData(){
    for node in ${AllNode[@]};do
        AllNodeDict[$node]=$(docker-machine ip $node)
    done
}

# 创建集群
create_cluster(){
    echo Creating cluster master
    for node in ${AllNode[@]};do
        ip=${AllNodeDict[$node]}
        clusterList=$( for i in ${!AllNodeDict[@]};do  echo $i=http://${AllNodeDict[$i]}:2380; done | sort | paste -d, -s - )
        docker $(docker-machine config $node) run -d --name etcd \
        -p 2379:2379 \
        -p 2380:2380 \
        --volume=etcd-data:/etcd-data \
        registry.aliyuncs.com/google_containers/etcd:3.3.10 \
        etcd --data-dir=/etcd-data --name $node \
        --initial-advertise-peer-urls http://$ip:2380 --listen-peer-urls http://0.0.0.0:2380 \
        --advertise-client-urls http://$ip:2379 \
        --listen-client-urls http://0.0.0.0:2379 \
        --initial-cluster-state new \
        --initial-cluster-token docker-etcd \
        --initial-cluster $clusterList

    done
}

# 查看集群健康
checkClusterHealth(){
    etcd_servers=$( for i in ${!AllNodeDict[@]};do  echo http://${AllNodeDict[$i]}:2379; done | sort | paste -d, -s - )
    docker $(docker-machine config manager1) exec -it etcd /bin/sh -c "export ETCDCTL_API=2  && etcdctl --endpoints $etcd_servers cluster-health"
}


# 关闭集群
teardown(){
    for node in ${AllNode[@]};do
        docker-machine rm -y $node
    done
}


case $1 in
    up)
        create_cluster_mathine
        createDictData
        create_cluster
        ;;
    down)
        teardown
        ;;
    check)
        createDictData
        checkClusterHealth
        ;;
    *)
        echo "Unknow command..."
        exit 1
        ;;
esac

